int counter=0;
while ( counter < 10 )
{
System.out.println("counter is now " + counter );
counter++ ;
}
The postfix increment operator ++
adds one to a variable.
Usually the variable is an integer type (byte, short, int, or long)
but it can be a floating point type (float or double).
No character is allowed between the two plus signs.
The postfix operator must follow the variable. Usually it is put immediately adjacent to the variable, as above, although this is not necessary.
The postfix increment operator can be used as part of an arithmetic expression, as in the following:
int sum = 0; int counter = 10; sum = counter++ ; System.out.println("sum: " + sum + " counter: " + counter );
This program fragment will print:
sum: 10 counter: 11
The statement sum = counter++;
increments the variable counter
after
it has been used.
It is vital to understand the details of this:
=
counter
has not been incremented yet.)=
++
operator works: counter
is incremented to 11.sum: 10 counter: 11
This is confusing.
It is best to use the ++
operator
only with variables that are not part of a larger expression,
as in the answer to the previous question.
The Java AP Examination
does not use
this operator in expressions
or in assignment statements.
However, it does
use the operator to increment
isolated integer variables.
It does not use the operator with
floats or doubles.
Inspect the following code:
int x = 99; int y = 10; y = x++ ; System.out.println("x: " + x + " y: " + y );
What does the above program print?